<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUploadAvatarService } from '@/api/user'
import pageContainer from '@/components/PageContainer.vue'

const userStore = useUserStore()

const uploadRef = ref()
const imgUrl = ref(userStore.user.user_pic)
// 将图片转成base64
const onUploadFile = (file) => {
  console.log(file)
  // 校验图片格式
  if (!['image/jpeg', 'image/png'].includes(file.raw.type)) {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return
  }

  // 校验图片大小
  if (file.raw.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!')
    return
  }

  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}

// 图片上传前 校验
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile)
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!')
    return false
  }
  return true
}
// 上传头像
const onUpdateAvatar = async () => {
  // await beforeAvatarUpload
  console.log(imgUrl.value)
  await userUploadAvatarService(imgUrl.value, userStore.user.id)
  await userStore.getUser()
  ElMessage({ type: 'success', message: '更换头像成功' })
}
</script>

<template>
  <page-container title="更换头像">
    <el-row>
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <el-button
          type="primary"
          @click="uploadRef.$el.querySelector('input').click()"
          :icon="Plus"
          size="large"
        >
          选择图片
        </el-button>
        <el-button type="success" @click="onUpdateAvatar" :icon="Upload" size="large">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
